<?php


namespace app\api\controller\v1;

use app\common\controller\Api;
use think\Db;
use think\Validate;

/**
 *  教练接口
 */
class Coach extends Api
{

    protected $noNeedLogin = ['index'];
    protected $noNeedRight = '*';
    protected static $sex = [
        1 => '男',
        2 => '女',
        3 => '保密',
    ];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 教练列表、详情：传入教练主键返回详情，这时其它参数无效，传入场馆主键返回列表
     * @ApiMethod (GET)
     * @param int $id 教练主键：id
     * @param int $gymnasium_id 场馆主键：gymnasium_id
     */
    public function index()
    {
        if ($this->request->isGet()) {

            $gymnasium_id = input('gymnasium_id');
            $id           = input('id');

            if (!$gymnasium_id && !$id) {
                $this->error('必传一个参数');
            }

            if ($id) {
                $result = Db::name('coach')
                    ->where(['id' => $id])
                    ->field('speciality_ids,video,user_id,gymnasium_id,name,phone,sex,images,speciality,cases_images,portrait_image,status,content_,likes,collections')
                    ->find();

                if ($result) {
                    $result['status'] != 1 && $this->error('获取失败,教练已被禁用');
                    unset($result['status']);
                    $result['portrait_image'] = self::patch_cdn($result['portrait_image']);
                    $result['cases_images']   = self::patch_cdn($result['cases_images']);
                    $result['images']         = self::patch_cdn($result['images']);
                    $result['video']          = self::patch_cdn($result['video']);
                    $result['sex_text']       = self::$sex[$result['sex']];
                    $result['is_like']        = false;
                    $result['is_fabulous']    = false;

                    // 用户登录了才会判断 是否收藏了该教练
                    if ($this->auth->isLogin()) {
                        $find = Db::name('user_like')->where(['user_id' => $this->auth->id, 'coach_id' => $id])->find();
                        if ($find) {
                            $result['is_like'] = true;
                        }
                    }

                    // 用户登录了才会判断 是否收点赞了该教练
                    if ($this->auth->isLogin()) {
                        $find = Db::name('user_fabulous')->where(['user_id' => $this->auth->id, 'coach_id' => $id])->find();
                        if ($find) {
                            $result['is_fabulous'] = true;
                        }
                    }

                    // 擅长课程
                    $speciality_ids = Db::name('category')->whereIn('id', $result['speciality_ids'])->field('name')->select();
                    if (count($speciality_ids) > 0) {
                        $speciality = [];
                        foreach ($speciality_ids as $i => $v) {
                            $speciality[$i] = $v['name'];
                        }
                        $result['speciality'] = implode(',',$speciality);
                    }
                    $this->success('获取成功', $result);
                } else {
                    $this->error('获取失败,教练信息不存在');
                }
            } else {
                $result = Db::name('coach')
                    ->where(['gymnasium_id' => $gymnasium_id, 'status' => 1])
                    ->order('likes', 'desc')
                    ->field('id,user_id,gymnasium_id,name,phone,sex,speciality,portrait_image,content_,collections,speciality_ids')
                    ->paginate(null, false, $this->paginate)
                    ->each(function ($item) {
                        $speciality_ids = Db::name('category')->whereIn('id', $item['speciality_ids'])->field('name')->select();
                        if (count($speciality_ids) > 0) {
                            $speciality = [];
                            foreach ($speciality_ids as $i => $v) {
                                $speciality[$i] = $v['name'];
                            }
                            $item['speciality'] = implode(',',$speciality);
                        }
                        $item['portrait_image'] = self::patch_cdn($item['portrait_image']);
                        $item['sex_text']       = self::$sex[$item['sex']];
                        return $item;
                    });
            }

            $this->success('获取成功', $result);
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 教练入驻
     * @ApiMethod (POST)
     * @param int $gymnasium_id 场馆主键：gymnasium_id
     * @param string $name 姓名
     * @param string $phone 联系电话
     * @param int $sex 性别:1=男,2=女,3=保密
     * @param string $speciality 擅长课程
     * @param string $images 照片轮播
     * @param string $portrait_image 教练肖像
     * @param string $card_up_image 身份证正面
     * @param string $card_down_image 身份证反面
     * @param string $content 教练介绍
     */
    public function create()
    {
        if ($this->request->isPost()) {

            $data = [
                'user_id'         => $this->auth->id,
                'gymnasium_id'    => input('gymnasium_id'),
                'name'            => input('name'),
                'phone'           => input('phone'),
                'sex'             => input('sex'),
                'speciality'      => input('speciality'),
                'images'          => input('images', ''),
                'portrait_image'  => input('portrait_image'),
                'card_up_image'   => input('card_up_image'),
                'card_down_image' => input('card_down_image'),
                'content_'        => input('content'),
                'createtime'      => time(),
                'updatetime'      => time(),
            ];

            $rule = [
                'user_id'         => 'require|unique:coach',
                'gymnasium_id'    => 'checkGymnasium:1',
                'name'            => 'require|max:8|min:2',
                'phone'           => 'require|length:11|unique:coach',
                'sex'             => 'require|between:1,3',
                'speciality'      => 'require|max:20',
                'portrait_image'  => 'require',
                'card_up_image'   => 'require',
                'card_down_image' => 'require',
                'content_'        => 'require|max:250',
            ];

            $msg = [
                'user_id.unique'          => '你已经提交过审核',
                'name.require'            => '请输入名称',
                'name.max'                => '名称最多8个字符',
                'name.min'                => '名称最少2个字符',
                'phone.require'           => '请填写手机号',
                'phone.length'            => '手机号长度不正确',
                'phone.unique'            => '手机号已存在',
                'sex.require'             => '请选择性别',
                'sex.between'             => '请选择正确的性别',
                'speciality.require'      => '请输入擅长课程',
                'speciality.max'          => '擅长课程最多20个字符',
                'portrait_image.require'  => '请上传肖像照',
                'card_up_image.require'   => '请上传身份证正面',
                'card_down_image.require' => '请上传身份证反面',
                'content_.require'        => '请输入教练介绍',
                'content_.max'            => '教练介绍最多250个字符',
            ];

            $validate = new Validate($rule, $msg);
            // 教练入驻需要验证场馆状态
            $validate->extend('checkGymnasium', function ($value) {
                $find = Db::name('gymnasium')->where(['id' => $value, 'status' => 1])->field('id')->find();
                return $find ? true : '场馆不存在，或已被禁用';
            });

            if (true === $validate->check($data)) {
                Db::startTrans();
                try {
                    $find              = Db::name('gymnasium')->where(['id' => input('gymnasium_id')])->field('longitude,latitude')->find();
                    $data['longitude'] = $find['longitude'];
                    $data['latitude']  = $find['latitude'];

                    Db::name('coach')->insert($data);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }

                $this->success('提交成功，请等待场馆审核');
            } else {
                $this->error($validate->getError());
            }
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }

    /**
     * 教练点赞
     * @ApiMethod (GET)
     * @param int $id 教练主键：id
     */
    public function likes()
    {
        if ($this->request->isGet()) {

            $id = input('id');

            !$id && $this->error('请传入教练主键');

            $find = Db::name('user_fabulous')->where(['user_id' => $this->auth->id, 'coach_id' => $id, 'type' => 2])->find();
            if ($find) {
                $operate = Db::name('user_fabulous')->delete(['id' => $find['id']]);
                if ($operate > 0) {
                    Db::name('coach')->where(['id' => $id])->setDec('likes');
                    $this->success('取消点赞');
                }
            } else {
                $operate = Db::name('user_fabulous')->insert([
                    'user_id'    => $this->auth->id,
                    'coach_id'   => $id,
                    'type'       => 2,
                    'createtime' => time()
                ]);
                if ($operate) {
                    Db::name('coach')->where(['id' => $id])->setInc('likes');
                    $this->success('点赞成功');
                }
            }
        } else {
            $this->error(ErrorCode::$ERROR['ERROR_METHOD']);
        }
    }
}
